package com.net.xpay.backend.scheduler;


import com.google.common.collect.Lists;
import com.net.common.concurrent.ThreadUtil;
import com.net.xpay.core.domain.PayTransSummary;
import com.net.xpay.core.enums.PayTransBatchStatus;
import com.net.xpay.core.manager.PayTransSummaryManager;
import com.net.xpay.core.service.PayTransBatchService;
import com.net.shard.ShardDataSource;
import com.net.shard.ShardDataSourceConfigurer;
import com.net.shard.ShardUtil;
import com.net.shard.domain.ShardConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 2019/7/15 16:28

 */
@Slf4j
@Component
public class PayTransScheduler {

    @Autowired
    private PayTransSummaryManager payTransSummaryManager;

    @Autowired
    @Qualifier("shardDataSource")
    private DataSource shardDataSource;

    @Autowired
    private PayTransBatchService payTransBatchService;

    /**
     * 查询交易状态
     */
    @Scheduled(cron = "*/10 * * * * *")
    public void updatePayTransSummary() {
        ShardDataSourceConfigurer shardDataSourceConfigurer = ((ShardDataSource) shardDataSource).getShardDataSourceConfigurer();
        Map<Long, ShardConfig> shardConfigMap = shardDataSourceConfigurer.getShardConfigMap();
        for (Long shardId : shardConfigMap.keySet()) {
            try {
                ShardUtil.setShardContext(shardId);
                doUpdatePayTransSummary();
            } catch (Exception e) {
                log.warn("updatePayTransSummary error", e);
            } finally {
                ShardUtil.cleanShardContext();
            }
        }
    }

    private void doUpdatePayTransSummary() {
        LocalDateTime minCreateTime = LocalDateTime.now().minusHours(72L);
        LocalDateTime maxCreateTime = LocalDateTime.now().minusMinutes(2L);
        List<PayTransSummary> payTransSummaries = payTransSummaryManager.listByStatuses(Lists.newArrayList(PayTransBatchStatus.WAIT_PAY), minCreateTime, maxCreateTime);

        if (CollectionUtils.isEmpty(payTransSummaries)) {
            return;
        }

        for (PayTransSummary summary : payTransSummaries) {
            try {
                payTransBatchService.updatePayTransBatch(summary.getUserId(), summary.getId());
                ThreadUtil.safeSleep(200L, "doUpdatePayTransSummary sleep some time");
            } catch (Exception e) {
                log.warn("doUpdatePayTransSummary failed|summaryId={}|userId={}", summary.getId(), summary.getUserId(), e);
            }
        }
    }
}
